/*
 *所有关于Basicdata_Product类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*Basicdata_ProductService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using iMES.Basedata.IRepository.Basicdata;
using iMES.Core.BaseProvider;
using iMES.Core.Extensions;
using iMES.Core.Extensions.AutofacManager;
using iMES.Core.Utilities;
using iMES.Custom.IRepositories;
using iMES.Entity.DomainModels;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Net;

namespace iMES.Basedata.Services
{
    public partial class Basicdata_ProductService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IBasicdata_ProductRepository _repository;//访问数据库
        private readonly IBase_NumberRuleRepository _numberRuleRepository;//自定义编码规则访问数据库
        [ActivatorUtilitiesConstructor]
        public Basicdata_ProductService(
            IBasicdata_ProductRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
             IBase_NumberRuleRepository numberRuleRepository
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _numberRuleRepository = numberRuleRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }



        WebResponseContent webResponse = new WebResponseContent();

        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            // 添加前的处理
            AddOnExecuting = (Basicdata_Product product, object list) =>
            {
                // 如果产品编号为空，自动生成编号
                if (string.IsNullOrWhiteSpace(product.ProductCode))
                {
                    product.ProductCode = GetProductCode();
                }

                // 验证编号是否重复
                if (repository.Exists(x => x.ProductCode == product.ProductCode))
                {
                    return webResponse.Error("产品编号已存在");
                }

                // 验证名称是否重复
                if (repository.Exists(x => x.ProductName == product.ProductName))
                {
                    return webResponse.Error("产品名称已存在");
                }

                return webResponse.OK();
            };

            return base.Add(saveDataModel);
        }

        /// <summary>
        /// 自动生成产品编号
        /// </summary>
        private string GetProductCode()
        {
            DateTime dateNow = (DateTime)DateTime.Now.ToString("yyyy-MM-dd").GetDateTime();

            // 查询当天最新的产品编号
            string lastCode = repository.FindAsIQueryable(x => x.CreateDate > dateNow && x.ProductCode.Length > 8)
                .OrderByDescending(x => x.ProductCode)
                .Select(s => s.ProductCode)
                .FirstOrDefault();

            // 查询编号规则
            Base_NumberRule numberRule = _numberRuleRepository.FindAsIQueryable(x => x.FormCode == "Product")
                .OrderByDescending(x => x.CreateDate)
                .FirstOrDefault();

            if (numberRule != null)
            {
                string rule = numberRule.Prefix + DateTime.Now.ToString(numberRule.SubmitTime.Replace("hh", "HH"));

                // 如果是当天第一个编号
                if (string.IsNullOrEmpty(lastCode))
                {
                    rule += "1".PadLeft(numberRule.SerialNumber, '0');
                }
                else
                {
                    // 获取序号并加1
                    rule += (lastCode.Substring(lastCode.Length - numberRule.SerialNumber).GetInt() + 1)
                        .ToString("0".PadLeft(numberRule.SerialNumber, '0'));
                }
                return rule;
            }

            // 如果没有配置编号规则，使用时间戳
            return "P" + DateTime.Now.ToString("yyyyMMddHHmmssffff");
        }


    }


    






}
